package com.hc.conferencecheck.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.conferencecheck.entity.*;
import com.hc.conferencecheck.entity.entityDTO.*;
import com.hc.conferencecheck.mapper.*;
import com.hc.conferencecheck.service.AttendRecordService;
import com.hc.conferencecheck.service.ConferenceService;
import com.hc.conferencecheck.service.ImageService;
import com.hc.conferencecheck.utils.PageHelperUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 会议对象service实现类
 */
//开启事务管理
@Transactional
@Service
public class ConferenceServiceImpl implements ConferenceService {
    public static final Logger logger = LoggerFactory.getLogger(ConferenceServiceImpl.class);
    @Resource
    private ConferenceMapper conferenceMapper;
    @Resource
    private AttendRecordService attendRecordServiceImpl;
    @Resource
    private AttendRecordMapper attendRecordMapper;
    @Resource
    private QrCodeMapper qrCodeMapper;
    @Resource
    private ConferenceAddressMapper conferenceAddressMapper;
    @Resource
    private AttendRecordBranchMapper attendRecordBranchMapper;
    @Resource
    private ImageService imageServiceImpl;

    /**
     * 根据用户ID查询该用户所有某状态的申请记录
     */
    public ResultMsg selectConferenceInfoByConventionerId(Map<String, Object> params) {
        List<ConferenceDetailDTO02> conferenceDetailDTO02s = conferenceMapper.selectConferenceInfoByConventionerId(params);
        if (conferenceDetailDTO02s != null && conferenceDetailDTO02s.size() > 0) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conferenceDetailDTO02s);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "数据为空");
        }
    }

    /**
     * 查询所有会议的所有审核还未通过的记录（审核未通过，审核中）
     */
    public List<ConferenceDetailDTO> selectAttendRecordNotApproved(Map<String, Object> params) {
        List<ConferenceDetailDTO> conferenceDetailDTOS = conferenceMapper.selectAttendRecordNotApproved(params);
        return conferenceDetailDTOS;
    }


    /**
     * 查询所有的会议对象
     *
     * @return
     */
    public ResultMsg selectAllConference(Map<String, Object> params) {
        //处理分页参数
        //获取分页参数
        Object pageNumberObj = params.get("pageNumber");
        int pageNumber = 0;
        if (pageNumberObj != null) {
            pageNumber = Integer.parseInt(pageNumberObj.toString());
        }
        PageHelper.startPage(pageNumber, 20);
        //
        ConferenceExample example = new ConferenceExample();
        ConferenceExample.Criteria criteria = example.createCriteria();
        criteria.andIdIsNotNull();
        List<Conference> conferences = conferenceMapper.selectByExample(example);

        if (conferences != null && conferences.size() > 0) {
            //获取总记录数
            PageInfo<Conference> pageInfo = new PageInfo<Conference>(conferences);
            long pageTotal = pageInfo.getTotal();
            // 用总条数获取总页数
            pageTotal = (pageTotal + 20 - 1) / 20;


            Map<String, Object> result = new HashMap<>();
            result.put("dataList", conferences);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            logger.error("会议对象为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议对象为空");
        }
    }


    /**
     * 会议后台管理页面查询会议详情
     *
     * @param params
     * @return
     */
    public ResultMsg selectConferenceInfo(Map<String, Object> params) {
        List<ConferenceDetailDTO02> conferenceDetailDTO02s = conferenceMapper.selectConferenceInfo(params);
        if (conferenceDetailDTO02s == null || conferenceDetailDTO02s.size() == 0) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "数据为空");
        } else {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conferenceDetailDTO02s);
        }
    }


    /**
     * 查询当前用户所有可签到会议
     */
    public ResultMsg selectBranchAddressAllowSign(Integer conventionerId) {
        //查询当前用户所有已申请会议
        List<ConferenceAppliedDTO> conferenceAppliedDTOS = conferenceMapper.selectConferenceApplied(conventionerId);

        if (conferenceAppliedDTOS == null || conferenceAppliedDTOS.size() == 0) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "没有可签到会议");
        }
        //查询当前用户所有可签到分会场
        List<ConferenceAddress> conferenceAddresses = conferenceAddressMapper.selectBranchAllowSign(conventionerId);

        if (conferenceAddresses == null || conferenceAddresses.size() == 0) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "没有可签到会议");
        }
        //添加分会场信息到每场会议对象中
        for (ConferenceAppliedDTO conferenceAppliedDTO : conferenceAppliedDTOS) {
            Integer id = conferenceAppliedDTO.getId();
            List<ConferenceAddress> branchList = conferenceAppliedDTO.getBranchList();
            for (ConferenceAddress conferenceAddress : conferenceAddresses) {
                Integer conferenceId = conferenceAddress.getConferenceId();
                if (conferenceId == id) {
                    //添加
                    branchList.add(conferenceAddress);
                } else {
                    continue;
                }
            }
        }

        return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conferenceAppliedDTOS);
    }

    /**
     * “我的会议申请”模块中的会议详情
     */
    public ResultMsg selectConferenceByIds(Map<String, Object> params) {
        //首先查询会议详情
        List<ConferenceDetailDTO> conferenceDetailDTOS = attendRecordMapper.selectAttendRecordByIds(params);

        //查询分会场详情
        List<ConferenceAddressDTO> conferenceAddresses = attendRecordBranchMapper.selectAttendRecordByIds(params);

        Map<String, Object> result = new HashMap<>();
        result.put("conference", conferenceDetailDTOS);
        result.put("branches", conferenceAddresses);

        return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
    }


    /**
     * 查询当前用户所有已申请会议
     */
    public List<ConferenceAppliedDTO> selectConferenceApplied(Integer conventionerId) {
        List<ConferenceAppliedDTO> conferenceAppliedDTOS = conferenceMapper.selectAllConferenceByConventionerId(conventionerId);
        return conferenceAppliedDTOS;
    }

    /**
     * 修改会议对象
     */
    public ResultMsg editConference(Conference conference, List<ConferenceAddress> addressList) {
        //修改会议对象
        int i = conferenceMapper.updateByPrimaryKeySelective(conference);
        Integer conferenceId = conference.getId();
        //修改会议分会场对象
        //首先删除原分会场信息
        ConferenceAddressExample example = new ConferenceAddressExample();
        ConferenceAddressExample.Criteria criteria = example.createCriteria();
        criteria.andConferenceIdEqualTo(conferenceId);
        conferenceAddressMapper.deleteByExample(example);
        // 然后添加新的分会场信息
        for (ConferenceAddress conferenceAddress : addressList) {
            conferenceAddress.setConferenceId(conferenceId);
        }
        int i1 = conferenceAddressMapper.insertBatch(addressList);

        if (i == 1 && i1 == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "修改成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "修改失败");
        }
    }

    /**
     * 删除会议对象
     */
    public ResultMsg deleteConferenceByPrimaryKey(int conferenceId) {
        //删除会议记录
        int i = conferenceMapper.deleteByPrimaryKey(conferenceId);
        //删除服务器上的图片
        imageServiceImpl.deleteImageFormServer(1, conferenceId);
        //删除会议收钱码数据库记录
        QrCodeExample example = new QrCodeExample();
        QrCodeExample.Criteria criteria = example.createCriteria();
        criteria.andIdentifyIdEqualTo(conferenceId);
        criteria.andTypeEqualTo(1);
        qrCodeMapper.deleteByExample(example);

        //删除会议分会场
        ConferenceAddressExample example1 = new ConferenceAddressExample();
        ConferenceAddressExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andConferenceIdEqualTo(conferenceId);
        conferenceAddressMapper.deleteByExample(example1);

        if (i == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "删除成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "删除失败");
        }
    }

    /**
     * 修改会议对象
     */
    public ResultMsg createConference02(Conference conference, List<ConferenceAddress> addressList, MultipartFile file, Integer conferenceId) {
        //保存会议基础信息
        int i = conferenceMapper.insertSelective(conference);
        //保存会议分会场信息
        for (ConferenceAddress conferenceAddress : addressList) {
            //设置分会场中的会议ID
            conferenceAddress.setConferenceId(conferenceId);
        }
        int i1 = conferenceAddressMapper.insertBatch(addressList);

        //上传图片到服务器
        ResultMsg resultMsg = imageServiceImpl.uploadImageToServer(file, 1, conferenceId);
        int code = resultMsg.getCode();

        if (i == 1 && i1 == 1 && code == 200) {
            //返回主键
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conferenceId);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "添加失败");
        }
    }

    /**
     * 添加会议对象
     */
    public ResultMsg createConference(Conference conference, List<ConferenceAddress> addressList, MultipartFile file) {
        //保存会议基础信息
        int i = conferenceMapper.insertSelective(conference);
        Integer conferenceId = conference.getId();
        //保存会议分会场信息
        for (ConferenceAddress conferenceAddress : addressList) {
            //设置分会场中的会议ID
            conferenceAddress.setConferenceId(conferenceId);
        }
        int i1 = conferenceAddressMapper.insertBatch(addressList);

        //上传图片到服务器
        ResultMsg resultMsg = imageServiceImpl.uploadImageToServer(file, 1, conferenceId);
        int code = resultMsg.getCode();

        if (i == 1 && i1 == 1 && code == 200) {
            //返回主键
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), conferenceId);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "添加失败");
        }
    }

    /**
     * 申请报名会议接口
     */
    public ResultMsg applyConference(Map<String, Object> params) {
        //获取申请者ID和会议ID
        Object conventionerIdObj = params.get("conventionerId");
        if (conventionerIdObj == null) {
            logger.error("申请者ID不可为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "申请者ID不可为空");
        }
        int conventionerId = Integer.parseInt(conventionerIdObj.toString());
        //获取要申请的会议的ID
        Object conferenceIdObj = params.get("conferenceId");
        if (conferenceIdObj == null) {
            logger.error("会议ID不可为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议ID不可为空");
        }
        int conferenceId = Integer.parseInt(conferenceIdObj.toString());
        //根据用户ID和会议ID查询是否有此申请记录
//        AttendRecord attendRecord = attendRecordServiceImpl.selectAttendRecordByDoubleId(conventionerId, conferenceId);
//        if (attendRecord != null) {
//            //可以查询到该用户对于当前会议的申请记录，需要提示不可重复申请
//            logger.error("不可重复申请");
//            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "不可重复申请");
//        }
        //获取支付账号；支付金额
        Object payAccountObj = params.get("payAccount");
        if (payAccountObj == null) {
            logger.error("支付账号不可为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "支付账号不可为空");
        }
        String payAccount = payAccountObj.toString();
        Object amountOfPayObj = params.get("amountOfPay");
        if (amountOfPayObj == null) {
            logger.error("支付金额不可为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "支付金额不可为空");
        }
        String amountOfPay = amountOfPayObj.toString();
        Long amountOfPayL = Long.valueOf(amountOfPay);

        //添加会议申请记录
        AttendRecord newAttendRecord = new AttendRecord();
        newAttendRecord.setConventionerId(conventionerId);
        newAttendRecord.setConferenceId(conferenceId);
        newAttendRecord.setApplyTime(new Date());
        //未支付，未签到，申请未通过；
//        newAttendRecord.setIsSign((byte) 0);
        newAttendRecord.setIsPay((byte) 0);
        newAttendRecord.setIsApproved((byte) 2);
        newAttendRecord.setPayAccount(payAccount);
        newAttendRecord.setAmountOfPay(amountOfPayL);
        //插入会议申请记录
        int i = attendRecordMapper.insert(newAttendRecord);
        //插入分会场签到记录
        //首先查询该会议的所有分会场
        ConferenceAddressExample example = new ConferenceAddressExample();
        ConferenceAddressExample.Criteria criteria = example.createCriteria();
        criteria.andConferenceIdEqualTo(conferenceId);
        List<ConferenceAddress> conferenceAddresses = conferenceAddressMapper.selectByExample(example);

        List<AttendRecordBranch> branchList = new ArrayList<>();
        for (ConferenceAddress conferenceAddress : conferenceAddresses) {
            //获取分会场id
            Integer addressId = conferenceAddress.getId();
            //创建分会场签到记录
            AttendRecordBranch attendRecordBranch = new AttendRecordBranch();
            attendRecordBranch.setAddressId(addressId);
            attendRecordBranch.setConferenceId(conferenceId);
            attendRecordBranch.setConventionerId(conventionerId);
            attendRecordBranch.setStatus("0");

            branchList.add(attendRecordBranch);
        }
        int i1 = attendRecordBranchMapper.insertBatch(branchList);

        if (i == 1 && i1 == 1) {
            //申请成功，发送提示短信；
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "申请成功");
        } else {
            logger.error("申请失败");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "申请失败");
        }
    }

    /**
     * 根据主键查询会议对象
     */
    public ResultMsg selectConferenceByPrimaryKey(Map<String, Object> params) {
        //获取主键参数
        Object conferenceIdObj = params.get("conferenceId");
        if (conferenceIdObj == null) {
            logger.error("会议ID不可为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议ID不可为空");
        }
        String conferenceId = conferenceIdObj.toString();
        int conferenceIdInt = Integer.parseInt(conferenceId);

        Conference conference = conferenceMapper.selectByPrimaryKey(conferenceIdInt);

        if (conference == null) {
            logger.error("查询不到指定会议对象");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "查询不到指定会议对象");
        } else {
            //查询会议分会场对象集合
            ConferenceAddressExample example = new ConferenceAddressExample();
            ConferenceAddressExample.Criteria criteria = example.createCriteria();
            criteria.andConferenceIdEqualTo(conferenceIdInt);
            List<ConferenceAddress> conferenceAddresses = conferenceAddressMapper.selectByExample(example);

            Map<String, Object> result = new HashMap<>();
            result.put("conference", conference);
            result.put("addressList", conferenceAddresses);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        }
    }

    /**
     * 查询所有的有效会议对象
     */
    public ResultMsg selectAllConferences(Map<String, Object> params) {
        //获取当前用户的id
        Object userIdObj = params.get("userId");
        if (userIdObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "用户ID为空");
        }
        int userId = Integer.parseInt(userIdObj.toString());
        //处理分页参数
//        PageHelperUtils.startPage(params);

        List<ConferenceDTO> conferences = conferenceMapper.selectEffectiveConference(userId);

        if (conferences != null && conferences.size() > 0) {
            //获取总记录数
//            PageInfo<ConferenceDTO> pageInfo = new PageInfo<>(conferences);
//            long pageTotal = pageInfo.getTotal();
            Map<String, Object> result = new HashMap<>();
            result.put("dataList", conferences);
//            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            logger.error("会议对象为空");
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议对象为空");
        }
    }
}
